import sys
import os
import os.path
import shutil
import simplejson
import web.template

render = web.template.render('templates/')

def _generate_table(table_file):

    table = simplejson.load(open(table_file))

    output_path = 'output'
    proj_path = os.path.join('output', table['name'])
    src_path = os.path.join(proj_path, 'src')
    icons_path = os.path.join(src_path, 'icons')

    if not os.path.exists(output_path): os.mkdir(output_path)
    if not os.path.exists(proj_path): os.mkdir(proj_path)
    if not os.path.exists(src_path): os.mkdir(src_path)

    # Populate field displayNames
    for field in table['fields']:
        if not 'displayName' in field.keys():
            field['displayName'] = field['name'][0].upper() + field['name'][1:]

    # Generate <table>.mxml, <table>Script.as, <table>Config.as in src_path
    f = open(os.path.join(src_path, table['name'] + '.mxml'), 'w')
    f.write(str(render.table_mxml(table)))
    f.close()

    f = open(os.path.join(src_path, table['name'] + '.as'), 'w')
    f.write(str(render.table_as(table)))
    f.close()

    # Copy icons directory
    if os.path.exists(icons_path): shutil.rmtree(icons_path)
    os.mkdir(icons_path)
    shutil.copyfile(os.path.join('icons', 'AddRecord.png'), os.path.join(icons_path, 'AddRecord.png'))
    shutil.copyfile(os.path.join('icons', 'DeleteRecord.png'), os.path.join(icons_path, 'DeleteRecord.png'))
    shutil.copyfile(os.path.join('icons', 'SearchRecord.png'), os.path.join(icons_path, 'SearchRecord.png'))

if __name__ == '__main__':
    if len(sys.argv) == 2: _generate_table(sys.argv[1])
    else: print 'CRUD_gen_table.py <table_description_file>'